﻿#region Header
// Copyright 2007-2011, Jerónimo Milea
// 
// This file is part of NetJsWire.
// 
//     NetJsWire is free software: you can redistribute it and/or modify
//     it under the terms of the GNU General Public License as published by
//     the Free Software Foundation, either version 3 of the License, or
//     (at your option) any later version.
// 
//     NetJsWire is distributed in the hope that it will be useful,
//     but WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//     GNU General Public License for more details.
// 
//     You should have received a copy of the GNU General Public License
//     along with NetJsWire.  If not, see <http://www.gnu.org/licenses/>.
#endregion

using System;
using System.Configuration;
using System.Web.Configuration;

namespace NetJsWire.Direct.helper
{
    public static class ConfigurationCache
    {
        static private string cachedRouterUrl = "";

        static public string getRouterUrl() 
        {
            return getRouterUrl(false);
        }

        /// <summary>
        ///   trys to find the configured handler for the router
        /// </summary>
        /// <param name = "clear">clear Cache and reload config</param>
        /// <returns>returns the url to the Ext Direct Router</returns>
        static public string getRouterUrl(bool clear)
        {
            if (!clear && cachedRouterUrl != "")
            {
                return cachedRouterUrl;
            }
            var routerUrl = "";

            // readout the system.web/httpHandlers secion in the webconfig this dll is bound. 
            // This is needed to mapp to the correct router url...
            var httpHandlers = ConfigurationManager.GetSection( "system.web/httpHandlers" ) as HttpHandlersSection;

            // now itterate over all the available actions and find the one containing the url.
            foreach ( HttpHandlerAction curHandler in httpHandlers.Handlers )
            {
                // search for the handler link to the router class.
                if ( curHandler.Type.IndexOf( "NetJsWire.Direct.DirectRouter" ) != -1 )
                {
                    routerUrl = curHandler.Path;
                    break;
                }
            }

            if ( routerUrl == "" )
            {
                throw new Exception( "Configuration for the DirectRouter wasn't found. "
                    + "Please add e.g.<add verb=\"*\" path=\"directRouter.rfc\" type=\"ExtDirect4DotNet.DirectProxy,ExtDirect4DotNet\" /> to your web.config"
                );
            }

            return routerUrl;
        }
    }
}
